import glob
import os, sys

en_keypoints = [
    "nose",
    "left_eye",
    "right_eye",
    "left_ear",
    "right_ear",
    "left_shoulder",
    "right_shoulder",
    "left_elbow",
    "right_elbow",
    "left_wrist",
    "right_wrist",
    "left_hip",
    "right_hip",
    "left_knee",
    "right_knee",
    "left_ankle",
    "right_ankle"
]

keypoints = [
    "鼻子",
    "左眼",
    "右眼",
    "左耳",
    "右耳",
    "左肩",
    "右肩",
    "左手肘",
    "右手肘",
    "左手腕",
    "右手腕",
    "左胯部",
    "右胯部",
    "左膝",
    "右膝",
    "左脚踝",
    "右脚踝"
]

keypoints_style = [
    "#e6194b",
    "#3cb44b",
    "#ffe119",
    "#0082c8",
    "#f58231",
    "#911eb4",
    "#46f0f0",
    "#f032e6",
    "#d2f53c",
    "#fabebe",
    "#008080",
    "#e6beff",
    "#aa6e28",
    "#fffac8",
    "#800000",
    "#aaffc3",
    "#808000"
]

categories = [{
    "id" : "1",
    "name" : "person",
    "supercategory" : "person",
    #"skeleton": skeleton,
    "keypoints" : keypoints,
    "keypoints_style" : keypoints_style
}]

import cv2
import numpy as np
from tqdm import tqdm
import json
from PIL import Image

import socket
import shutil
import hashlib

def get_host_ip():
  """
  查询本机ip地址
  :return: ip
  """
  try:
      s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      s.connect(('8.8.8.8', 80))
      ip = s.getsockname()[0]
  finally:
      s.close()

  return ip
  
def CalcSha1(filepath):
    with open(filepath,'rb') as f:
        sha1obj = hashlib.sha1()
        sha1obj.update(f.read())
        hash = sha1obj.hexdigest()
        #print(hash)
        return hash
 
def CalcMD5(filepath):
    with open(filepath,'rb') as f:
        md5obj = hashlib.md5()
        md5obj.update(f.read())
        hash = md5obj.hexdigest()
        #print(hash)
        return hash

ip = get_host_ip()
#print(ip)

image_dirs = []

port = int(sys.argv[1])
server_root_path = sys.argv[2]
outputFileName = sys.argv[3]

for i in range(4, len(sys.argv)):

    for parent, _, _ in os.walk(sys.argv[i], topdown=False):
      if not parent in image_dirs:
        image_dirs.append(parent)

#print("image_dirs is ", image_dirs)

images = []
image_id = 0

sum = 0

if os.path.exists(outputFileName):
  shutil.rmtree(outputFileName)
os.makedirs(outputFileName)

for image_dir in image_dirs:

  image_dir_regx = image_dir + os.sep + '*.jpg'
  inputImages = glob.glob(image_dir_regx)
  dirName = image_dir.split(server_root_path)[1]
  
  if len(inputImages) ==  0:
    continue
  
  sum += len(inputImages)
  print(image_dir)
  #continue
  #sys.exit(-1)
  
  image_dir_regx_desc = tqdm(inputImages)

  #for image_path in glob.glob(image_dir_regx):
  for image_path in image_dir_regx_desc:
  
      image_file_name = os.path.basename(image_path)
      image_hash = CalcMD5(image_path)
      
      new_image_path = outputFileName + os.sep + image_hash + '.jpg'
      
      shutil.copy(image_path, new_image_path)
      
      #img = cv2.imread(image_path)
      img = Image.open(image_path)
      imgSize = img.size
      
      height =  img.height #height(rows) of image
      width = img.width #width(colums) of image

      #print(image_path)
      #print(height)
      #print(width)
      #sys.exit(-1)
      #image_id = os.path.splitext(image_file_name)[0]
      image_url = "http://{}:{}/{}".format(ip, port, '' if len(dirName) == 0 else dirName+'/') + image_file_name
      
      image_id += 1
      
      #print(image_url)
      images.append({
          "id" : image_id,
          "file_name" : image_file_name,
          "url" : image_url,
          "width" : width,
          "height" : height,
          "rights_holder": dirName,
          "directory": dirName,
      })
  
  image_dir_regx_desc.close()

dataset = {
    "categories" : categories,
    "images" : images,
    "annotations" : [],
    "licenses" : []
}

dataset_file_path = outputFileName + "_dataset.json"
with open(dataset_file_path, 'w') as f:
    json.dump(dataset, f, sort_keys=True, indent=4, separators=(',', ': '))

print("The Json file have {num} images.".format(num=sum))
    